package com.ds.esd.bpm.custom.plugins.attachment;

import com.ds.bpm.client.ActivityInst;
import com.ds.bpm.client.ProcessInst;
import com.ds.bpm.client.ct.CtBPMCacheManager;
import com.ds.bpm.engine.WorkflowClientService;
import com.ds.bpm.enums.process.ProcessInstAtt;
import com.ds.common.JDSException;
import com.ds.common.md5.MD5InputStream;
import com.ds.common.util.StringUtility;
import com.ds.config.ListResultModel;
import com.ds.config.ResultModel;
import com.ds.enums.db.MethodChinaName;
import com.ds.esd.dsm.domain.annotation.BpmDomain;
import com.ds.esd.dsm.domain.enums.BpmDomainType;
import com.ds.esd.custom.annotation.DialogAnnotation;
import com.ds.esd.custom.annotation.GridViewAnnotation;
import com.ds.esd.custom.api.annotation.APIEventAnnotation;
import com.ds.esd.custom.api.enums.CustomCallBack;
import com.ds.esd.custom.enums.CustomMenuItem;
import com.ds.esd.custom.module.annotation.DynLoadAnnotation;
import com.ds.esd.custom.module.annotation.ModuleAnnotation;

import com.ds.jds.core.esb.EsbUtil;
import com.ds.vfs.FileInfo;
import com.ds.vfs.Folder;
import com.ds.vfs.ct.CtVfsFactory;
import com.ds.vfs.ct.CtVfsService;
import com.ds.web.annotation.Aggregation;
import com.ds.web.annotation.AggregationType;
import com.ds.web.util.PageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/bpm/plugins/attachment/")
@MethodChinaName(cname = "附件", imageClass = "spafont spa-icon-newfile")
@BpmDomain(type = BpmDomainType.custom)
@Aggregation(type = AggregationType.customDomain,sourceClass =AttachMentService.class )
public class AttachMentService {

    @MethodChinaName(cname = "获取附件列表")
    @GridViewAnnotation()
    @ModuleAnnotation(caption = "获取附件列表")
    @RequestMapping(method = RequestMethod.POST, value = "GetAttacheMentList")
    @APIEventAnnotation(bindMenu = {CustomMenuItem.gridReload})
    public @ResponseBody
    ListResultModel<List<AttachMentView>> getAttacheMentList(String activityInstId, String activityInstHistoryId, String formname) {
        ListResultModel<List<AttachMentView>> resultModel = new ListResultModel<List<AttachMentView>>();
        try {
            if (activityInstId != null) {
                List<FileInfo> attachMents = new ArrayList<>();
                ActivityInst inst = getClient().getActivityInst(activityInstId);
                String processInstId = null;
                if (inst != null) {
                    processInstId = inst.getProcessInstId();
                }
                Folder processInstFolder = this.getProcessFolder(processInstId);
                if (inst.isCanPerform()) {
                    if (activityInstHistoryId != null) {
                        Folder activityInstHisFolder = (Folder) getVfsClient().getFolderByPath(processInstFolder.getPath() + activityInstId + "/" + activityInstHistoryId + "/" + formname + "/attachment");
                        if (activityInstHisFolder != null) {
                            List<FileInfo> fileInfos = activityInstHisFolder.getFileList();
                            attachMents.addAll(fileInfos);
                        }
                    }
                } else {
                    Folder activityInstFolder = getVfsClient().getFolderByPath(processInstFolder.getPath() + activityInstId + "/" + formname + "/attachment");
                    attachMents.addAll(activityInstFolder.getFileList());
                }
                resultModel = PageUtil.getDefaultPageList(attachMents, AttachMentView.class);
            }
        } catch (JDSException e) {
            e.printStackTrace();
        }
        return resultModel;
    }


    @MethodChinaName(cname = "上传附件")
    @RequestMapping(method = RequestMethod.POST, value = "UPLoadView")
   @DynLoadAnnotation
    @DialogAnnotation
    @ModuleAnnotation(caption = "上传附件", cache = false,
            width = "400", height = "300")
    @APIEventAnnotation(bindMenu = {CustomMenuItem.add}, callback = {CustomCallBack.ReloadParent, CustomCallBack.Close})
    public @ResponseBody
    ResultModel<UPLoadView> upLoadView(String activityInstId, String formname) {
        ResultModel<UPLoadView> resultModel = new ResultModel<UPLoadView>();
        return resultModel;
    }


    public ResultModel<FileInfo> upload(MultipartFile file, String activityInstId, String formname, String files_fullname) {
        ResultModel<FileInfo> resultModel = new ResultModel<FileInfo>();
        try {
            ActivityInst inst = CtBPMCacheManager.getInstance().getActivityInst(activityInstId);
            String path = getProcessFolder(inst.getProcessInstId()).getPath() + inst.getActivityInstId() + "/" + formname + "/attachment";
            Folder foleder = this.getVfsClient().mkDir(path);
            FileInfo fileInfo = foleder.createFile(files_fullname, null);
            CtVfsFactory.getCtVfsService().upload(fileInfo.getPath(), new MD5InputStream(file.getInputStream()), null);
            resultModel.setData(fileInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultModel;
    }


    @MethodChinaName(cname = "删除附件")
    @RequestMapping(method = RequestMethod.POST, value = "delAttacheMent")
    @APIEventAnnotation(callback = {CustomCallBack.Reload}, bindMenu = CustomMenuItem.delete)
    public @ResponseBody
    ResultModel<Boolean> delAttacheMent(String path) {
        ResultModel<Boolean> resultModel = new ResultModel<Boolean>();
        String[] pathArr = StringUtility.split(path, ";");
        List<FileInfo> fileInfos = new ArrayList<FileInfo>();
        try {
            for (String filepath : pathArr) {
                FileInfo file = CtVfsFactory.getCtVfsService().getFileByPath(filepath);
                CtVfsFactory.getCtVfsService().deleteFile(file.getID());
            }
        } catch (JDSException e) {
            e.printStackTrace();
        }

        return resultModel;

    }

    Folder getProcessFolder(String processInstId) throws JDSException {
        ProcessInst processInst = getClient().getProcessInst(processInstId);
        String processInstFolderId = processInst.getAttribute(ProcessInstAtt.ROOTFOLDERID.getType());
        Folder processInstFolder = null;
        if (processInstFolderId != null) {
            processInstFolder = (Folder) this.getVfsClient().getFolderById(processInstFolderId);
        }
        return processInstFolder;
    }


    public CtVfsService getVfsClient() {

        CtVfsService vfsClient = CtVfsFactory.getCtVfsService();
        return vfsClient;
    }


    /**
     * @return
     */
    public WorkflowClientService getClient() {
        WorkflowClientService client = ((WorkflowClientService) EsbUtil.parExpression("$BPMC"));
        return client;
    }
}
